#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "protocol.hpp"

int main(int argc, char*  argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "ip port" << std::endl;
        exit(1);
    }
    std::string server_ip = argv[1];
    int server_port = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cerr << "sock fail" << std::endl;
        exit(2);
    }

    struct sockaddr_in peer;
    memset(&peer, '\0', sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(server_port);
    peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
    if(connect(sock, (struct sockaddr*)&peer, sizeof(peer)) < 0)
    {
        std::cout << "connet fail" << std::endl;
        exit(3);
    }


    while(true)
    {
        //发起请求;
        request_t rq;
        std::cout << "请输入左操作数# " << std::endl;
        std::cin >> rq.x;
        std::cout << "请输入右操作数# " << std::endl;
        std::cin >> rq.y;
        std::cout << "请输入需要进行的操作[+-*/%] # " << std::endl;
        std::cin >> rq.op;
        send(sock, &rq, sizeof(rq), 0);

        //接收结果:
        response_t rp;
        recv(sock, &rp, sizeof(rp), 0);
        std::cout << "status: " << rp.code << std::endl;
        std::cout << rq.x << " " << rq.op << " "  << rq.y << " = " << rp.result << std::endl;
    }

    return 0;
}